package com.charon.common.security.listener;

import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.charon.module.sys.dao.UserEntityMapper;
import com.charon.module.sys.entity.UserEntity;

/**
 * @ClassName：CustomFormAuthenticationFilter.java
 * @Description:
 * @Author charon [248135724@qq.com]
 * @Date: 2019年1月6日 下午7:52:15
 * @version V1.0
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

	@Autowired
	private UserEntityMapper uem;
	
	/**
	 * 在登录成功时将用户信息存储到Session中。 
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		// 获取已登录的用户信息
		String userName = (String) subject.getPrincipal();
		System.out.println("CustomFormAuthenticationFilter类加载");
		// 获取session
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		HttpSession session = httpServletRequest.getSession();
		UserEntity ue = new UserEntity();
		ue.setAccount(userName);
		List<UserEntity> users = uem.findList(ue);
		if(users!=null&&users.size()>0){
			// 把用户信息保存到session
			session.setAttribute("user", users.get(0));	
		}
		return super.onLoginSuccess(token, subject, request, response);
	}

}
